﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace VTLive.Models
{
    public class StationRepository
    {
        VTliveDataContext db = new VTliveDataContext();

        public IQueryable<Station> GetAllStations()
        {
            return db.Stations;
        }

        public Station GetStation(int StationID)
        {
            return db.Stations.SingleOrDefault(s => s.ID == StationID);
        }

        public void Add(Station station)
        {
            db.Stations.InsertOnSubmit(station);
        }

        public Station InsertAndGetNewStation(Station station)
        {
            db.Stations.InsertOnSubmit(station);
            db.SubmitChanges();
            return station;
        }

        public void Delete(Station station)
        {
            db.Stations.DeleteOnSubmit(station);
        }

        public void Save()
        {
            db.SubmitChanges();
        }

        internal IQueryable<Station> GetAllOwnedStations(int? id)
        {         
            return  (from station in db.Stations
                     where station.OwnerID == id
                     select station);
        }


        internal bool IsOwnerOf(int? UserID, int StationID)
        {
            Station result = (from station in db.Stations
                              where station.ID == StationID &&
                                    station.OwnerID == UserID
                              select station).SingleOrDefault();

            return result != null;
        }

        internal IQueryable<Station> GetAllAssociatedStations(int? UserID)
        {
            return (from station in db.Stations
                    join associate in db.Associates
                    on station.ID equals associate.StationID
                    where associate.UserID == UserID
                    select station).Distinct();
        }
    }
}